<!--
 * @Author: zhangduo 445629906@qq.com
 * @Date: 2023-12-06 12:35:28
 * @LastEditors: zhangduo 445629906@qq.com
 * @LastEditTime: 2023-12-25 03:45:58
 * @FilePath: \mdbj-ui\src\views\mypage\roadmanage\roadsurface\editPanel.vue
 * @Description: 
 * 
 * Copyright (c) 2023 by zhangduo, All Rights Reserved. 
-->
<template>
  <div>
    <el-row>
      <el-col :span="24" class="title-row">
        <span :style="{ color: theme }">| 修改道路面信息</span>
      </el-col>
      <el-col :span="24">
        <!-- 组件依赖feature属性，所以需要等feature有值后再渲染-->
        <el-form
          id="elForm"
          ref="elForm"
          :model="formData"
          :rules="rules"
          size="medium"
          label-width="92px"
          v-if="formData"
        >
          <el-row>
            <el-col :span="12">
              <el-form-item label="道路名称" prop="name">
                <el-input
                  v-model="formData.name"
                  disabled
                  clearable
                  :style="{ width: '100%' }"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="道路编号" prop="roadnumber">
                <el-input
                  v-model="formData.roadnumber"
                  clearable
                  disabled
                  :style="{ width: '100%' }"
                ></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="道路功能" prop="roadfunction">
                <el-select
                  v-model="formData.roadfunction"
                  placeholder="请选择道路功能"
                  clearable
                  :style="{ width: '100%' }"
                >
                  <el-option
                    v-for="dict in dict.type.sys_roadfunction"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  ></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-form-item
            class="footer"
            size="medium"
            style="display: flex; justify-content: center"
          >
            <el-button type="primary" @click="submitForm" icon="el-icon-check"
              >提交</el-button
            >
            <el-button
              type="primary"
              plain
              icon="el-icon-circle-close"
              @click="cancel"
              >返回</el-button
            >
          </el-form-item>
        </el-form>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import roadsurfaceDataPanel from "../roadsurface/dataPanel";
import Graphic from "@arcgis/core/Graphic";
import GraphicsLayer from "@arcgis/core/layers/GraphicsLayer";
import Sketch from "@arcgis/core/widgets/Sketch";
export default {
  props: {
    paramObj: { default: () => {} },
    mapview: { default: () => {} },
  },
  dicts: ["sys_roadfunction"],
  inject: ["toggleComponent"],
  components: {
    roadsurfaceDataPanel: roadsurfaceDataPanel,
  },
  data() {
    return {
      featureId: undefined,
      roadcode: undefined,
      feature: undefined,
      formData: undefined,
      featureLayer: undefined,
      layerView: undefined,
      activeName: "roadPanel",
      // 内容样式
      contentStyle: {
        "text-align": "left",
        // "min-width": "320px", //最小宽度
        "word-break": "break-all", //过长时自动换行
      },
      // label样式
      labelStyle: {
        // width: "100px",
        "text-align": "left",
        "min-width": "120px",
        width: "150px",
        // "background-color": "#1682e621",
      },
      highlight: undefined,
      // 当前页正在编辑的要素
      feature: undefined,
      rules: undefined,
      featureLayer: undefined,
      selectedGraphic: undefined,
      udpateGraphicsLayer: undefined,
      addGraphics: [],
    };
  },
  computed: {
    theme() {
      return this.$store.state.settings.theme;
    },
  },
  /**
   * @description: 首次加载先触发created然后再mounted，所以需要再mounted之前的created里先initData
   * @return {*}
   */
  created() {
    console.log("created");
  },
  mounted() {
    console.log("mounted");
    // this.initData();
  },
  /**
   * @description: 之后的每次点击均触发activated，所以再调用一遍initData
   * @return {*}
   */
  activated() {
    console.log("activated");
    this.initData();
  },
  deactivated() {
    let _self = this;
    console.log("deactivated");
    _self.highlight?.remove();
    // 移除道路面图层
    _self.mapview.map.layers.remove(_self.featureLayer);
    _self.featureLayer = undefined;
    _self.feature = undefined;
    _self.layerView = undefined;
    _self.roadcode = undefined;
    _self.activeName = "roadPanel";
  },
  methods: {
    /**
     * @description: 初始化数据
     * @return {*}
     */
    initData() {
      let _self = this;
      console.log(_self.paramObj);
      _self.feature = _self.paramObj.feature;
      _self.formData = _self.feature.attributes;
      _self.featureLayer = _self.paramObj.featureLayer;
      _self.mapview.map.add(_self.featureLayer, 1);
      // _self.formData = {
      //   objectid: _self.feature.attributes.objectid,
      //   name: "道路名称改",
      //   // code: "ba695de8-1ef4-4e4f-86fe-f14a889e2609",
      //   roadnumber: "道路编号改",
      //   roadfunction: "9",
      //   cleancompany: "未分配",
      //   data_status: "1",
      // };
      // _self.locate(_self.feature);
      _self.updateGeometry();
    },

    locate(feature) {
      let _self = this;
      // 移除前一个高亮图形
      _self.highlight?.remove();
      // 高亮显示当前页要素;?
      _self.highlight = _self.layerView.highlight(feature);
      if (feature.geometry == null) {
        _self.$message.error("暂无空间信息");
        return;
      }
      _self.mapview
        .goTo({
          target: feature.geometry,
          // zoom: _self.zoomLevel,
        })
        .catch((error) => {
          if (error.name != "AbortError") {
            console.error(error);
          }
        });
    },
    submitForm() {
      let _self = this;
      console.log(_self.formData);
      _self.$refs["elForm"].validate((valid) => {
        if (!valid) return;
        if (_self.selectedGraphic == undefined) {
          _self.$message.error("请添加空间位置信息");
          return;
        }
        // 新增要素
        const editFeature = new Graphic({
          geometry:
            _self.selectedGraphic == undefined
              ? ""
              : _self.selectedGraphic.geometry,
          attributes: _self.formData,
        });
        const edits = {
          updateFeatures: [editFeature],
        };
        _self.featureLayer.applyEdits(edits).then((editsResult) => {
          console.log(editsResult);
          // if (_self.selectedGraphic)
          //   _self.udpateGraphicsLayer.remove(_self.selectedGraphic);
          // const objectId = editsResult.addFeatureResults[0].objectId;
          // // 根据返回的objectid添加附件
          // _self.addAttachment(attachGroupId);
          _self.$message.success("修改成功");
          _self.cancel();
        });
      });
    },
    // 更新空间位置
    updateGeometry() {
      let _self = this;
      _self.udpateGraphicsLayer = new GraphicsLayer();
      _self.mapview.map.add(_self.udpateGraphicsLayer);
      _self.sketch = new Sketch({
        layer: _self.udpateGraphicsLayer,
        view: _self.mapview,
        // graphic will be selected as soon as it is created
        creationMode: "update",
      });
      // 设置绘图工具条显示要素
      _self.sketch.visibleElements = {
        createTools: {
          point: false,
          polyline: false,
          polygon: true,
          rectangle: false,
          circle: false,
        },
        selectionTools: {
          "lasso-selection": false,
          "rectangle-selection": false,
        },
        settingsMenu: false,
      };
      // 指定要更新的图形
      _self.selectedGraphic = new Graphic({
        geometry: _self.feature.geometry,
        symbol: window.mapConfig.symbols.polygonLocate,
      });
      _self.udpateGraphicsLayer.add(_self.selectedGraphic);
      _self.sketch.update(_self.selectedGraphic);
      _self.mapview.ui.add(_self.sketch, "top-right");
      _self.sketch.when(() => {
        // 初始时先隐藏创建图形按钮
        // 每个要素只有一个点，如果已创建的一个点，则不允许继续创建点。隐藏创建点按钮
        document.getElementsByClassName(
          "esri-sketch__section esri-sketch__tool-section"
        )[1].style.display = "none";
      });

      _self.sketch.on("create", (event) => {
        if (event.state === "complete") {
          console.log("create complete");
          _self.selectedGraphic = event.graphic;
          _self.addGraphics.push(event.graphic);
          // 每个要素只有一个点，如果已创建的一个点，则不允许继续创建点。隐藏创建点按钮
          if (_self.addGraphics.length > 0)
            document.getElementsByClassName(
              "esri-sketch__section esri-sketch__tool-section"
            )[1].style.display = "none";
          // _self.mapview.graphics.add(event.graphic);
          // _self.mapview.ui.remove(_self.sketch);
        }
      });

      _self.sketch.on("update", (event) => {
        if (event.state === "complete") {
          console.log("Sketch complete");
          _self.mapview.graphics.add(event.graphics);
          // _self.mapview.ui.remove(_self.sketch);
        }
      });
      _self.sketch.on("delete", (event) => {
        event.graphics.forEach((graphic) => {
          console.log("deleted", graphic);
          if (graphic == _self.selectedGraphic)
            _self.selectedGraphic = undefined;
          _self.addGraphics = _self.addGraphics.filter(
            (item) => item !== graphic
          );
        });
        // 如果没有添加任何点，就显示创建点按钮
        if (_self.addGraphics.length == 0)
          document.getElementsByClassName(
            "esri-sketch__section esri-sketch__tool-section"
          )[1].style.display = "";
      });
    },
    clearGraphics() {
      let _self = this;
      _self.addGraphics = [];
      // 删除临时图形
      if (_self.selectedGraphic) {
        _self.udpateGraphicsLayer.remove(_self.selectedGraphic);
        _self.mapview.graphics.removeAll();
      }
      _self.mapview.map.layers.remove(_self.udpateGraphicsLayer);
    },
    cancel() {
      let _self = this;
      _self.addGraphics = [];
      // 删除临时图形
      if (_self.selectedGraphic)
        _self.udpateGraphicsLayer.remove(_self.selectedGraphic);
      _self.mapview.graphics.removeAll();
      // 移除临时图层
      _self.mapview.map.layers.remove(_self.udpateGraphicsLayer);
      // 删除微件
      _self.mapview.ui.remove(_self.sketch);
      const paramObj = {
        activeName: "roadsurfacePanel",
      };
      this.toggleComponent("roadEditPanel", paramObj);
    },
  },
};
</script>

<style lang="scss" scoped>
.title-row {
  width: 100%;
  font-size: 18px;
  font-weight: bold;
  color: #409eff;
  margin-bottom: 1vh;
}

.footer {
  margin-top: 1vh;
  margin-bottom: 1vh;
  display: flex;
  justify-content: center;
}
</style>
